package com.example.myblog.controller;

import com.example.myblog.pojo.Article;
import com.example.myblog.pojo.Comment;
import com.example.myblog.pojo.User;
import com.example.myblog.service.ArticleService;
import com.example.myblog.service.CommentService;
import com.example.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @BelongsProject: MyBlog
 * @BelongsPackage: com.example.myblog.controller
 * @ClassName BackendController
 * @CreateTime: 2025-05-31  18:22
 * @Author: TangLiFei
 */
@Controller
public class BackendController {
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;

    @RequestMapping("/backend")
    public String backend(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            model.addAttribute("errorMsg", "请先登录！");
            return "error";
        }
        // 验证是否为管理员
        if (user.getAuthorities() == null || !user.getAuthorities().contains("ROLE_admin")) {
            model.addAttribute("errorMsg", "仅允许管理员访问后台！");
            return "error";
        }
        //管理员允许访问
        System.out.println("访问后台管理页面");
        return "backend";
    }
    // 后台文章管理页面
    @GetMapping("/Articlebackend")
    public String list(Model model) {
        List<Article> articles = articleService.findAll();
        model.addAttribute("articles", articles);
        return "articleBackend";
    }

    // 后台评论管理页面
    @GetMapping("/Commentbackend")
    public String showCommentManagement(Model model) {
        List<Comment> comments=commentService.findAll();
        model.addAttribute("comments", comments);
        return "commentBackend";
    }

    // 后台用户管理页面
    @GetMapping("/Userbackend")
    public String userManagement(Model model) {
        List<User> users = userService.findAllUsers();
        model.addAttribute("users", users);
        return "userList";
    }

    // 注销用户
    @GetMapping("/deleteUser")
    public String deleteUser(@RequestParam("id") Integer id) {
        userService.deleteUserById(id);
        return "forward:/Userbackend";
    }
}
